package com.hmdp.service.impl;

import com.hmdp.entity.SeckillVoucher;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SeckillVoucherServiceImpl extends ServiceImpl<SeckillVoucherMapper, SeckillVoucher> implements ISeckillVoucherService {


    @Override
    public Boolean updateStockWithOrder(Long voucherId) {
        // 查询秒杀优惠券信息
        SeckillVoucher seckVoucher = query().eq("voucher_id", voucherId).one();
        if (seckVoucher == null) {
            System.out.println("未找到voucherId为" + voucherId + "的秒杀优惠券");
            return false;
        }

        int stockNumber = seckVoucher.getStock();
        if (stockNumber <= 0) {
            System.out.println("voucherId为" + voucherId + "的库存已不足");
            return false;
        }

        int updateNumber = stockNumber - 1;
        System.out.println("原库存：" + stockNumber + " 更新库存：" + updateNumber);

//        // 方案1: 使用UpdateWrapper只更新stock字段
//        boolean updateResult = update(new UpdateWrapper<SeckillVoucher>()
//                .set("stock", updateNumber)
//                .eq("voucher_id", voucherId));

        // 方案2: 如果方案1不行，使用实体更新（确保实体有主键）
         seckVoucher.setStock(updateNumber);
         boolean updateResult = updateById(seckVoucher);
         System.out.println("更新结果：" + updateResult);

        return true;
    }

}
